#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/4/12 16:45
# @Author : 闫峰
# @File    : discount_syc_check.py
from common.setting import ensure_path_sep
from third_services.shopee.discount.discount import InterfaceDiscount
from utils.mysqlUtils.db_pool import Database
from utils.otherutils.count_time import timer_decorator, remove_log, remove_dir_log
from utils.logging_tool.log_control import ERROR, WARNING, INFO


java_database = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "java_database")
dis = InterfaceDiscount()


def discount_syc_check(ordersourceid):
    """通过渠道id 返回折扣活动表id,platform_discount_id 元祖"""
    page_no = 1
    discount_list_res = []

    while True:
        res = dis.get_discount_list(ordersourceid, page_no)
        try:
            if res["response"] == {'more': False}:
                break
            else:
                discount_list = res['response']['discount_list']
                for i in discount_list:
                    discount_list_res.append(i)
                page_no += 1
        except:
            print(f"KeyError: 'response' res:{res}")
            break

    discount_list = []
    for discount in discount_list_res:
        discount_list.append(discount['discount_id'])
    in_res = tuple(discount_list)
    sql1 = """SELECT * FROM zhcxkj_center_promotion.t_shopee_discount WHERE platform_discount_id IN %s;"""
    res1 = java_database.fetch_all(sql1, (in_res,))


    shopee_discount_id_list = []
    if not res1:
        return []
    for discount in res1:
        shopee_discount_id_list.append((discount['id'], discount['platform_discount_id']))
    return shopee_discount_id_list


def discountlisting_syc_check(ordersourceid, shopee_discount_id, platform_discount_id, page_size):
    """验证折扣活动同步"""
    page_no = 1
    count = 0
    ERROR.logger.error(f"活动{platform_discount_id}开始验证")

    while True:

        res = dis.get_discount(ordersourceid, platform_discount_id, page_no)
        while True:
            if res['error'] == 'error_sign':
                res = dis.get_discount(ordersourceid, platform_discount_id, page_no)
            else:
                break
        # 代表这个活动下目前没有商品,验证数据库 t_shopee_discount_product没有数据
        if res.get("response") == None:
            print(res)
        if res["response"].get("item_list") is None:

            sql3 = f"""SELECT item_id,model_id,original_price,sale_price,quality,`status`
                    FROM zhcxkj_center_promotion.t_shopee_discount_product
                    WHERE shopee_discount_id={shopee_discount_id} and is_delete=0"""
            res3 = java_database.fetch_all(sql3, ())
            if res3 == None:

                break
            else:
                ERROR.logger.error(f"{platform_discount_id}没有商品,但是数据库 t_shopee_discount_product 有数据")
                ERROR.logger.error(f"活动{platform_discount_id}验证结束")
                break
        # 代表这个活动下有商品,验证数据库 t_shopee_discount_product没有数据
        if res['response'].get("item_list") is not None:

            for i in res['response']['item_list']:
                count += 1
                print(f"验证{count}个")
                sql1 = f"""
                SELECT item_id,model_id,original_price,sale_price,quality,`status`,is_deleted
                FROM zhcxkj_center_promotion.t_shopee_discount_product
                WHERE shopee_discount_id={shopee_discount_id} AND item_id=%s and is_deleted=0;
                """
                sql2 = f"""
                SELECT item_id,model_id,original_price,sale_price,quality,`status`,is_deleted
                    FROM zhcxkj_center_promotion.t_shopee_discount_product
                    WHERE shopee_discount_id={shopee_discount_id} AND item_id=%s AND model_id=%s and is_deleted=0;
                """
                sql3 = """SELECT `status` FROM zhcxkj_center_product.t_shopee_listing_promotion WHERE item_id=%s;"""
                sql4 = """SELECT `status` FROM zhcxkj_center_product.t_shopee_listing_promotion WHERE item_id=%s AND model_id=%s;"""
                if i.get('model_list'):
                    # 变体
                    item_id = i['item_id']
                    model_list = i['model_list']
                    for model in model_list:
                        res2 = java_database.fetch_all(sql2, (i['item_id'], model['model_id']))
                        if len(res2) != 0:

                            res2 = res2[0]
                            if i['purchase_limit'] == res2['quality'] \
                                    and float(round(model['model_original_price'], 4)) == float(
                                round(res2["original_price"], 4)) \
                                    and float(round(model['model_promotion_price'], 4)) == float(
                                round(res2["sale_price"], 4))\
                                    and res2['is_deleted'] == 0:
                                pass
                            else:
                                ERROR.logger.error(f"{i}同步存在问题")
                        else:
                            ERROR.logger.error(f"变体item_id： {item_id} model_id： {model['model_id']}在本地数据库 t_shopee_discount_product 查询不到")


                if not i.get('model_list'):
                    # 单体
                    res1 = java_database.fetch_all(sql1, (i['item_id'],))
                    if len(res1) != 0:
                        res1 = res1[0]
                        if i['purchase_limit'] == res1['quality'] \
                                and float(round(i["item_original_price"], 4)) == float(round(res1["original_price"], 4)) \
                                and float(round(i["item_promotion_price"], 4)) == float(round(res1["sale_price"], 4))\
                                and res1['is_deleted'] == 0:
                            pass
                        else:
                            ERROR.logger.error(f"{i}同步存在问题")
                    else:
                        ERROR.logger.error(f"单体item_id： {i['item_id']}在本地数据库 t_shopee_discount_product 查询不到")

            if res['response']['more']:
                page_no += 1
            else:
                ERROR.logger.error(f"活动{platform_discount_id}验证结束")
                break



if __name__ == '__main__':
    # print(discount_syc_check(15101))
    # @timer_decorator
    # discountlisting_syc_check(14257, 23630, 713788800240025, 10)
    # sql1 = """SELECT id FROM `zhcxkj-center-data`.rb_order_source WHERE customer_id=1  AND order_source_type=97 AND is_active=1 AND is_delete=0 AND order_source_country != 'CN';"""
    # source_id_list = java_database.fetch_all(sql1, ())
    @timer_decorator
    def func(ordersourceid):
        ERROR.logger.error(f"渠道{ordersourceid}开始验证")
        res = discount_syc_check(ordersourceid)
        print(res)
        for i in res:
            discountlisting_syc_check(ordersourceid, *i, 10)

        ERROR.logger.error(f"渠道{ordersourceid}验证完成")
    # remove_dir_log(dir_path="D:\zhcx-service-test\logs")

    # for sourceid in source_id_list:
    #     func(sourceid['id'])

    func(15101)